﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.IO;
using GeneralDFS.BusinessLogical.Nodes;
using GeneralDFS.Common;
using GeneralDFS.DataEntity.Nodes;

namespace GeneralDFS.Client
{
    public class BalanceTest
    {
        private Client _client;
        private readonly List<NameNodeInfo> _nameNodeInfos;
        private Dictionary<string, int> _counts;  
        public BalanceTest(Client client)
        {
            _client = client;
            _nameNodeInfos = client.GetConfig().NameNodeInfos();
            _counts=new Dictionary<string, int>();
        }

        public void Excute(int num)
        {
            var file = File.CreateText("result-balance.txt");
            var count = num;
            var partCount = 0;
            foreach (var nameNodeInfo in _nameNodeInfos)
            {
                _counts.Add(nameNodeInfo.ServerName,0);
            }
            file.Write("DateTime");
            foreach (var i in _counts)
            {
                file.Write("|" + i.Key);
            }
            file.WriteLine();
            var random = new Random();
            var random2 = new Random();
            while (count-->0)
            {
                partCount++;
                var randomString = DFSUtils.GetRandomString(10);
                var randomLong = DFSUtils.GetHash(count.ToString(CultureInfo.InvariantCulture));
                
                var randomInt = random.Next(_nameNodeInfos.Count);

                var remoteObject = NameNode.GetInstance(_nameNodeInfos[randomInt]);
                var nameNodeInfo = remoteObject.FindSuccessor(randomLong);
                _counts[nameNodeInfo.ServerName]++;
                if (partCount == 50)
                {
                    partCount = 0;
                    file.Write(DateTime.Now.ToLongTimeString());
                    foreach (var i in _counts)
                    {
                        file.Write("|"+i.Value.ToString(CultureInfo.InvariantCulture));
                    }
                    file.WriteLine();
                }
            }
            file.Close();
        }
    }
}
